<template>
  <el-card shadow="never" class="chat-container">
    <h1>DeepSeek 聊天助手</h1>
    <div id="chat-box" ref="chatBox" class="chat-messages">
      <div v-for="(msg, index) in messages" :key="index" :class="['message', msg.role]">
        <div class="avatar-container" v-if="msg.role === 'assistant'">
          <div class="avatar">
            <img src="@/assets/deepseek.png" alt="DeepSeek Logo" />
          </div>
        </div>
        <div class="message-content">
          <div v-if="isLoading && index === messages.length - 1 && msg.role === 'assistant' && !msg.content" class="loading-message-inline">
            <img src="@/assets/loading.gif" alt="Loading..." class="loading-gif" />
          </div>
          <div v-else v-html="formatMarkdown(msg.content)" class="markdown-content"></div>
        </div>
      </div>
    </div>
    
    <!-- 输入框区域 -->
    <div class="chat-input-wrapper">
      <div class="chat-input">
        <el-input
            ref="inputField"
            v-model="userInput"
            type="textarea"
            :autosize="{ minRows: 1, maxRows: 4 }"
            placeholder="输入您的消息..."
            @keydown.enter.exact.prevent="sendMessage"
            @keydown.shift.enter.stop
        />
        <el-button type="primary" @click="sendMessage" :loading="isLoading" circle>
          <el-icon><send /></el-icon>
          {{ isLoading ? '生成中...' : '发送' }}
        </el-button>
      </div>
    </div>
    
    <!-- 清除按钮 -->
    <el-popconfirm
      title="确定要清空所有聊天记录吗？"
      confirm-button-text="确定"
      cancel-button-text="取消"
      @confirm="clearChat"
    >
      <template #reference>
        <el-button type="danger" class="clear-chat-button" circle>
          <el-icon class="delete-icon"><delete /></el-icon>
        </el-button>
      </template>
    </el-popconfirm>
  </el-card>
</template>

<script setup>
import { ref, nextTick, onMounted, onBeforeUnmount } from 'vue';
import MarkdownIt from 'markdown-it';
import hljs from 'highlight.js';
import { chatAPI } from '@/api/admin/ai';
import { ElMessage } from 'element-plus';
import { debounce } from 'lodash-es';

// 定义用户输入
const userInput = ref('');
// 存储所有消息记录，每条消息包含角色和内容
const messages = ref([]);
// 加载状态
const isLoading = ref(false);
// 聊天框引用
const chatBox = ref(null);
// 输入框引用
const inputField = ref(null);
// 当前 EventSource 连接
let currentEventSource = null;
// 超时计时器
let timeoutTimer = null;
const connectionTimeout = 30000; // 30秒超时

// 创建 Markdown-it 实例
const md = new MarkdownIt({
  html: true,
  linkify: true,
  typographer: true,
  highlight: (str, lang) => {
    if (lang && hljs.getLanguage(lang)) {
      try {
        return `<pre class="hljs"><code>${
            hljs.highlight(str, {
              language: lang,
              ignoreIllegals: true
            }).value
        }</code></pre>`;
      } catch (__) {}
    }
    return `<pre class="hljs"><code>${md.utils.escapeHtml(str)}</code></pre>`;
  }
});

// 函数：将 Markdown 格式文本转换为 HTML 字符串
const formatMarkdown = (text) => {
  if (!text) return '';
  
  // 将Markdown转换为HTML
  const html = md.render(text);
  
  // 添加段落缩进
  return html.replace(/<p>/g, '<p style="text-indent: 2em; pointer-events: auto;">');
};

// 自动滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (chatBox.value) {
      chatBox.value.scrollTop = chatBox.value.scrollHeight;
    }
  });
};

// 关闭当前 EventSource 连接
const closeEventSource = () => {
  if (currentEventSource) {
    currentEventSource.close();
    currentEventSource = null;
  }
  
  // 清除计时器
  if (timeoutTimer) {
    clearTimeout(timeoutTimer);
    timeoutTimer = null;
  }
};

// 发送消息的异步函数，使用流式响应
const sendMessage = debounce(function() {
  const message = userInput.value.trim();
  if (!message || isLoading.value) return;
  
  // 保存当前消息并清空输入
  const currentMessage = message;
  userInput.value = '';  
  
  // 关闭之前的连接（如果存在）
  closeEventSource();

  // 将用户消息添加到聊天记录中
  messages.value.push({
    role: 'user',
    content: currentMessage,
  });
  
  // 确保滚动到底部并重新聚焦输入框
  nextTick(() => {
    scrollToBottom();
    // 引用可能访问的是组件实例而不是DOM元素
    setTimeout(() => {
      if (inputField.value) {
        // 尝试使用不同的方式获取输入框并聚焦
        try {
          const inputEl = inputField.value.$el.querySelector('textarea');
          if (inputEl) {
            inputEl.focus();
          } else if (inputField.value.focus) {
            inputField.value.focus();
          }
        } catch (e) {
          console.error('聚焦输入框失败:', e);
        }
      }
    }, 100);
  });

  // 创建新的助手回复（初始为空）
  messages.value.push({
    role: 'assistant',
    content: '',
  });
  
  // 当前正在接收的消息索引
  const currentMessageIndex = messages.value.length - 1;
  
  // 显示加载状态
  isLoading.value = true;
  
  // 重试相关变量
  let retryCount = 0;
  const maxRetries = 3;
  
  const createConnection = () => {
    try {
      console.log(`创建SSE连接，尝试次数: ${retryCount + 1}/${maxRetries}`);
      
      // 设置简单的超时处理
      if (timeoutTimer) clearTimeout(timeoutTimer);
      timeoutTimer = setTimeout(() => {
        console.error('SSE 连接超时');
        closeEventSource();
        isLoading.value = false;
        
        // 如果没有收到任何内容，添加错误消息
        if (!messages.value[currentMessageIndex].content) {
          messages.value[currentMessageIndex].content = 'AI服务响应超时，请稍后重试。';
          scrollToBottom();
        }
      }, connectionTimeout);

      // 创建 EventSource 连接
      currentEventSource = chatAPI.createStreamConnection(currentMessage);
      
      // 连接打开时的处理
      currentEventSource.onopen = () => {
        console.log('SSE连接已打开');
      };
      
      // 监听消息事件
      currentEventSource.onmessage = (event) => {
        try {
          // 收到消息后清除超时计时器
          if (timeoutTimer) {
            clearTimeout(timeoutTimer);
            timeoutTimer = null;
          }
          
          // 判断是否为结束标记
          if (event.data === 'end') {
            console.log('接收到结束标记');
            closeEventSource();
            isLoading.value = false;
            return;
          }
          
          // 解析收到的数据
          const data = JSON.parse(event.data);
          
          // 追加内容到当前回复
          if (data && data.content) {
            messages.value[currentMessageIndex].content += data.content;
            scrollToBottom();
          }
        } catch (error) {
          console.error('消息处理错误:', error);
        }
      };
      
      // 监听错误事件
      currentEventSource.onerror = (error) => {
        console.error('SSE 连接错误:', error);
        
        // 关闭当前连接
        closeEventSource();
        
        // 如果还有重试次数，尝试重新连接
        if (retryCount < maxRetries) {
          retryCount++;
          setTimeout(() => {
            console.log(`尝试重新连接 (${retryCount}/${maxRetries})...`);
            createConnection();
          }, 1000 * retryCount); // 逐步增加重试间隔
        } else {
          // 超过最大重试次数
          ElMessage.error('连接服务器失败，请稍后重试');
          isLoading.value = false;
          
          // 如果没有收到任何内容，添加错误消息
          if (!messages.value[currentMessageIndex].content) {
            messages.value[currentMessageIndex].content = '连接服务器失败，请稍后重试。可能原因：\n1. 网络连接问题\n2. DeepSeek服务暂时不可用\n3. 请求内容可能违反使用规则';
            scrollToBottom();
          }
        }
      };
    } catch (error) {
      console.error('创建 SSE 连接失败:', error);
      ElMessage.error(`连接失败: ${error.message}`);
      isLoading.value = false;
      
      // 如果没有收到任何内容，添加错误消息
      if (!messages.value[currentMessageIndex].content) {
        messages.value[currentMessageIndex].content = `连接失败: ${error.message}`;
        scrollToBottom();
      }
    }
  };
  
  // 初始化连接
  createConnection();
}, 300, { leading: true, trailing: false });

// 清除聊天记录的函数
const clearChat = () => {
  messages.value = [];
  userInput.value = ''; // 清空输入框
  closeEventSource();
  isLoading.value = false;
};

onMounted(() => {
  window.addEventListener('resize', scrollToBottom);
  scrollToBottom();
  
  // 初始聚焦输入框
  setTimeout(() => {
    if (inputField.value) {
      try {
        const inputEl = inputField.value.$el.querySelector('textarea');
        if (inputEl) {
          inputEl.focus();
        } else if (inputField.value.focus) {
          inputField.value.focus();
        }
      } catch (e) {
        console.error('初始聚焦输入框失败:', e);
      }
    }
  }, 300);
});

// 组件卸载前清理
onBeforeUnmount(() => {
  window.removeEventListener('resize', scrollToBottom);
  closeEventSource();
  
  // 清除计时器
  if (timeoutTimer) {
    clearTimeout(timeoutTimer);
    timeoutTimer = null;
  }
});
</script>

<style scoped>
/* 容器优化 */
.chat-container {
  width: 100%;
  height: calc(100vh - 64px); /* 减去顶部导航高度 */
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  font-family: 'Arial', sans-serif;
  box-shadow: none;
  border: none;
  background-color: #fff;
  position: relative; /* 改为相对定位 */
  z-index: 1; /* 确保不会覆盖顶部导航 */
}

.chat-container :deep(.el-card__body) {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 20px;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 0 20px;
  margin-bottom: 80px; /* 给输入框留出空间 */
  scroll-behavior: smooth;
}

/* 消息气泡优化 */
.message {
  display: flex;
  margin-bottom: 24px;
  opacity: 0;
  transform: translateY(20px);
  animation: messageAppear 0.3s ease forwards;
  align-items: flex-start;
}

.message.assistant {
  justify-content: flex-start;
  margin-right: 15%;
}

.message.user {
  justify-content: flex-end;
  margin-left: 15%;
}

.avatar-container {
  margin-right: 12px;
  width: 50px;
  display: flex;
  justify-content: center;
}

.avatar {
  width: 36px;
  height: 36px;
  background-color: #f0f2f5;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
}

.avatar img {
  width: 24px;
  height: 24px;
  object-fit: cover;
}

.message-content {
  max-width: calc(85% - 60px);
  padding: 12px 16px;
  border-radius: 12px;
  line-height: 1.6;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

/* 用户消息样式 */
.message.user .message-content {
  background: #409eff;
  color: white;
  border-radius: 12px 12px 0 12px;
}

/* AI 消息样式 */
.message.assistant .message-content {
  background: #f8f9fa;
  border: 1px solid #eee;
  border-radius: 12px 12px 12px 0;
}

/* Markdown 内容排版 */
.markdown-content {
  width: 100%;
}

/* 段落样式 */
.markdown-content :deep(p) {
  margin-bottom: 12px;
  text-align: justify;
  line-height: 1.7;
}

/* 标题样式 */
.markdown-content :deep(h1),
.markdown-content :deep(h2),
.markdown-content :deep(h3) {
  margin-top: 24px;
  margin-bottom: 16px;
  font-weight: 600;
  line-height: 1.25;
}

.markdown-content :deep(h1) {
  font-size: 1.5em;
  border-bottom: none;
  padding-bottom: 0.3em;
}

.markdown-content :deep(h2) {
  font-size: 1.3em;
  border-bottom: none;
  padding-bottom: 0.3em;
  margin-top: 24px;
  margin-bottom: 16px;
  display: flex;
  align-items: center;
}

.markdown-content :deep(h2)::before {
  content: "";
  display: inline-block;
  width: 4px;
  height: 1em;
  background-color: #333;
  margin-right: 8px;
}

.markdown-content :deep(h3) {
  font-size: 1.1em;
}

/* 列表样式 */
.markdown-content :deep(ul),
.markdown-content :deep(ol) {
  padding-left: 1.5em;
  margin-bottom: 16px;
  list-style-position: outside;
}

.markdown-content :deep(ul) {
  list-style-type: disc;
}

.markdown-content :deep(ol) {
  list-style-type: decimal;
}

.markdown-content :deep(li) {
  margin-bottom: 4px;
  line-height: 1.7;
  position: relative;
  display: list-item;
}

/* 嵌套列表项 */
.markdown-content :deep(li > ul),
.markdown-content :deep(li > ol) {
  margin-top: 4px;
  margin-bottom: 0;
}

.markdown-content :deep(li)::marker {
  color: #666;
}

.markdown-content :deep(li + li) {
  margin-top: 0.25em;
}

/* 列表符号 */
.markdown-content :deep(ul) {
  list-style-type: disc;
}

.markdown-content :deep(ul ul) {
  list-style-type: circle;
}

.markdown-content :deep(ul ul ul) {
  list-style-type: square;
}

/* 引用块 */
.markdown-content :deep(blockquote) {
  border-left: 4px solid #ddd;
  color: #666;
  padding: 0 1em;
  margin: 0 0 16px 0;
}

.markdown-content :deep(blockquote > :first-child) {
  margin-top: 0;
}

.markdown-content :deep(blockquote > :last-child) {
  margin-bottom: 0;
}

/* 水平线 */
.markdown-content :deep(hr) {
  height: 1px;
  padding: 0;
  margin: 24px 0;
  background-color: #e1e4e8;
  border: 0;
  position: relative;
  width: 100%;
}

/* 加载消息样式 */
.loading-message {
  display: flex;
  align-items: center;
  background: #f0f2f5;
  padding: 8px 16px;
  border-radius: 18px;
}

.loading-gif {
  height: 24px;
  width: auto;
}

/* 代码块专用样式 */
.markdown-content :deep(pre) {
  background: #1a1a1a !important;
  border-radius: 8px;
  padding: 16px !important;
  margin: 12px 0;
  border: 1px solid #333;
  overflow-x: auto;
}

.markdown-content :deep(code) {
  font-family: 'Menlo', 'Consolas', monospace !important;
  font-size: 14px;
  color: #c9d1d9;
}

/* 输入框容器 */
.chat-input-wrapper {
  position: absolute; /* 改为相对于chat-container的绝对定位 */
  bottom: 20px;
  left: 0;
  right: 0;
  display: flex;
  justify-content: center; /* 水平居中 */
  width: 100%;
  z-index: 9; /* 降低z-index值，避免遮挡顶部导航 */
}

/* 输入框区域优化 */
.chat-input {
  width: 80%; /* 控制输入框宽度，可以根据需要调整 */
  max-width: 800px;
  background: #fff;
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
  display: flex;
  gap: 12px;
  align-items: center;
}

.el-input {
  flex: 1;
}

.el-button {
  height: 40px;
  padding: 0 24px;
  border-radius: 4px;
}

@keyframes messageAppear {
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.chat-container h1 {
  text-align: center;
  margin-bottom: 20px;
}

.chat-container h1,
.chat-container h2,
.chat-container h3 {
  font-weight: bold;
  margin-top: 16px;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .chat-input {
    width: 90%;
    padding: 12px;
  }

  .message-content {
    max-width: calc(90% - 60px);
  }

  .el-button {
    padding: 0 15px;
  }

  .avatar {
    width: 32px;
    height: 32px;
  }
  
  .clear-chat-button {
    right: 15px;
    width: 35px;
    height: 35px;
  }
  
  .clear-chat-button .delete-icon {
    font-size: 16px;
  }
}

/* 加载消息样式 */
.loading-message-inline {
  display: flex;
  align-items: center;
  padding: 8px 0;
}

.loading-gif {
  height: 24px;
  width: auto;
}

/* 清除聊天记录按钮样式 */
.clear-chat-button {
  position: absolute; /* 改为相对于chat-container的绝对定位 */
  bottom: 27px; /* 微调使其与输入框水平对齐 */
  right: 30px;
  width: 40px;
  height: 40px;
  display: flex;
  justify-content: center;
  align-items: center;
  box-shadow: 0 4px 12px rgba(220, 53, 69, 0.3);
  z-index: 10; /* 降低z-index值，避免遮挡顶部导航 */
  transition: all 0.3s ease;
  background-color: #dc3545;
  border-color: #dc3545;
}

.clear-chat-button .delete-icon {
  font-size: 18px;
}

.clear-chat-button:hover {
  transform: rotate(15deg);
  box-shadow: 0 6px 15px rgba(220, 53, 69, 0.4);
  background-color: #c82333;
  border-color: #bd2130;
}

/* 内联代码 */
.markdown-content :deep(p code),
.markdown-content :deep(li code) {
  background-color: rgba(175, 184, 193, 0.2);
  padding: 0.2em 0.4em;
  margin: 0 0.2em;
  border-radius: 3px;
  font-family: 'Menlo', 'Consolas', 'Monaco', monospace;
  font-size: 85%;
  color: #333;
}

/* 项目符号前缀 */
.markdown-content :deep(ul li)::before {
  content: none;
}
</style>